package com.lanou.renrenxin.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.base.BaseActivity;
import com.lanou.renrenxin.tools.RenRenXinHelper;
import com.parse.ParseAnalytics;

/**
 * Created by dllo on 16/3/1.
 */
public class LoginActivity extends BaseActivity {
    private TextView textViewOne, textViewTwo;
    private EditText userNameEt, passWordEt;

    private boolean autoLogin = false;
    private boolean progressShow;

    private String currentUsername;
    private String currentPassword;

    /**
     * 检测网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context){
        if (context != null){
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null){
                return networkInfo.isAvailable() && networkInfo.isConnected();
            }
        }
        return false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ParseAnalytics.trackAppOpenedInBackground(getIntent());
        // 如果登录成功过，直接进入主页面
        if (RenRenXinHelper.getInstance().isLoggedIn()) {
            autoLogin = true;
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra("LOGIN_USER_NAME", EMChatManager.getInstance().getCurrentUser());
            startActivity(intent);
            return;
        }

        setContentView(R.layout.activity_login);

        //appLogo文字效果设置
        textViewOne = (TextView) findViewById(R.id.renRenXin);
        textViewTwo = (TextView) findViewById(R.id.jiShiTongXun);
        textViewOne.setRotationY(20);
        textViewTwo.setRotationY(-20);

        userNameEt = (EditText) findViewById(R.id.userName_login);
        passWordEt = (EditText) findViewById(R.id.passWord_login);

        // 如果用户名改变，清空密码
        userNameEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {
                passWordEt.setText(null);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        if (RenRenXinHelper.getInstance().getCurrentUsernName() != null){
            userNameEt.setText(RenRenXinHelper.getInstance().getCurrentUsernName());
        }
    }
    /**
     * 登录
     *
     * @param view
     */
    public void login(View view) {
        if (!isNetWorkConnected(this)) {
            Toast.makeText(this, "当前网络不可用！", Toast.LENGTH_SHORT).show();
            return;
        }
        currentUsername = userNameEt.getText().toString().trim();
        currentPassword = passWordEt.getText().toString().trim();

        if (TextUtils.isEmpty(currentUsername)) {
            Toast.makeText(this, "用户名不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(currentPassword)) {
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        //登录loading：ProgressDialog
        progressShow = true;
        final ProgressDialog pd = new ProgressDialog(LoginActivity.this);
        pd.setCanceledOnTouchOutside(false);
        pd.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                progressShow = false;
            }
        });
        pd.setMessage(getString(R.string.Is_landing));
        pd.show();

        final long start = System.currentTimeMillis();
        //调用sdk登陆方法登陆聊天服务器
        EMChatManager.getInstance().login(currentUsername, currentPassword, new EMCallBack() {
            @Override
            public void onSuccess() {
                if (!progressShow) {
                    return;
                }
                //登录成功，保存用户名
                RenRenXinHelper.getInstance().setCurrentUserName(currentUsername);

                if (!LoginActivity.this.isFinishing() && pd.isShowing()) {
                    pd.dismiss();
                }
                //进入主页面
                Intent intentLogin = new Intent(LoginActivity.this, MainActivity.class);
                intentLogin.putExtra("LOGIN_USER_NAME", currentUsername);
                startActivity(intentLogin);
                finish();
            }

            @Override
            public void onProgress(int i, String s) {

            }

            @Override
            public void onError(int i, String s) {
                if (!progressShow) {
                    return;
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.dismiss();
                        Toast.makeText(LoginActivity.this, "用户名或密码错误！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    /**
     * 注册
     *
     * @param view
     */
    public void register(View view) {
        startActivityForResult(new Intent(this, RegisterActivity.class), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (autoLogin) {
            return;
        }
    }
}
